package com.bnq.control.desktop.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.View;

import com.bnq.control.common.utils.DisplayUtils;
import com.oray.sunlogin.plugin.remotedesktop.RemoteDesktopJni;

/**
 * Created by zou on 2016/11/25.
 */

public class MoveDesktopTool extends View {
    public static int SCALE_NUM = 10;
    private float prey;
    private float width, height;

    private Context context;
    private ToolEvent toolEvent;
    private RemoteDesktopJni jni;
    private RectF dst;

    public MoveDesktopTool(Context context, RemoteDesktopJni jni, ToolEvent toolEvent) {
        super(context);
        this.context = context;
        this.jni = jni;
        this.width = DisplayUtils.getScreenWidth(context) * 1.0f / SCALE_NUM;
        this.height = DisplayUtils.getScreenWidth(context) * 1.0f / SCALE_NUM;
        this.toolEvent = toolEvent;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        width = DisplayUtils.getScreenWidth(context) * 1.0f / SCALE_NUM;
        height = DisplayUtils.getScreenHeight(context) * 1.0f / SCALE_NUM;
        canvas.save();
        Bitmap bitmap = scaleBitmap(jni.getBitmap(), jni.getBitmap().getWidth() / SCALE_NUM, jni.getBitmap().getHeight() / SCALE_NUM);
        if (null == dst) dst = new RectF(0, 0, width, height);
        canvas.drawBitmap(bitmap, null, dst, null);
        canvas.restore();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                prey = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                float dy = event.getY() - prey;
                toolEvent.onMove(dy);
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return true;
    }

    private Bitmap scaleBitmap(Bitmap src, int newwith, int newheight) {
        int width = src.getWidth();
        int height = src.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newwith) / width;
        float scaleHeight = ((float) newheight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        return Bitmap.createBitmap(src, 0, 0, width, height, matrix, true);
    }

    public int getViewWidth() {
        return (int) this.width;
    }

    public int getViewHeight() {
        return (int) this.height;
    }

    public interface ToolEvent {
        void onMove(float dy);
    }
}
